package com.xd.demo.interceptor;

import com.alibaba.fastjson.JSON;
import com.xd.demo.dto.JdResDto;
import com.xd.demo.process.ReqResProcessor;
import com.xd.demo.wrapper.RequestWrapper;
import com.xd.demo.wrapper.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

//@Component
public class CommonInterceptor implements HandlerInterceptor {

    /**
     * 存储当前请求的处理器
     */
    private ReqResProcessor currProcessor;

    /**
     * 注入所有已注册的处理器
     */
//    @Autowired
    private List<ReqResProcessor> reqResProcessors;

    /**
     * 请求前置处理方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestWrapper requestWrapper = (RequestWrapper) request;
        String reqBody = new String(requestWrapper.getReqBody());
        // 轮训所有处理器，选择支持的处理器处理
        for (ReqResProcessor processor : reqResProcessors) {
            if (processor.supports(reqBody)) {
                currProcessor = processor;
                try {
                    // reqBody 请求的内容 实例化为 ReqDto 转化为JSON
                    // ReqDto data 为字符串 应为对象
                    String newReqBody = currProcessor.reqBodyProcess(reqBody);
                    // request 把请求体赋值
                    requestWrapper.setReqBody(newReqBody.getBytes());
                    return true;
                } catch (Exception e) {
                    String resBody = currProcessor.exceptionProcess(reqBody);
                    response.getOutputStream().write(resBody.getBytes());
                    return false;
                }
            }
        }
        // TODO log.warn
        return false;
    }

}
